#include <algorithm>
#include <iostream>
#include "Master.h"
#include "TwoWayList.cc"

using namespace std;

//MasterImp::MasterImp(void)
MasterImp::MasterImp(string search,char *fileName)
#ifdef DEBUG_EVPROC
: EventProcessorImp(true,"Master") // comment to remove debug
#endif
{
  // register the message function

  RegisterMessageProcessor(DieMessage::type, &Die, 0 /* priority */);

  RegisterMessageProcessor(WorkerDoneMessage::type, &WorkerDone, 1 /* priority */);
  RegisterMessageProcessor(ReadyMessage::type, &WorkerReady, 2 /* priority */);
  
  RegisterMessageProcessor(DoneMessage::type, &SearchDone, 3 /* priority */);

	
  wordToSearch = search;
  myfile.open(fileName);	
  //ReadNextLine();
  currentLine = 0;
  counter = 0;

}

int MasterImp::ReadNextLine(string& line){
	//string line;
	if(!myfile.eof()){
		getline(myfile,line);
		lines.push_back(line);
		return 1;
	}
	else{
		cout<<"Finished reading all the lines "<<endl;
		return 0;
	}
}
void MasterImp::CheckAndSend(EventProcessor& sender){
		
	string xline;
	EventProcessor myInterfClone;
	myInterfClone.CopyFrom(myInterface);
	int returnValue = ReadNextLine(xline);
	if(returnValue == 0){
		KillEvProc(sender);
	}
	else{
		SearchMessage_Factory(sender,xline,wordToSearch,currentLine, myInterfClone);	
		++currentLine;
	}
}

MESSAGE_HANDLER_DEFINITION_BEGIN(MasterImp, SearchDone, DoneMessage)

	evProc.counter += msg.numTimes;	
	evProc.CheckAndSend(msg.sender);

MESSAGE_HANDLER_DEFINITION_END

//Workers are ready to do the sum, append them to the myWorkers list 

MESSAGE_HANDLER_DEFINITION_BEGIN(MasterImp, WorkerReady, ReadyMessage)

	evProc.CheckAndSend(msg.sender);

MESSAGE_HANDLER_DEFINITION_END

MESSAGE_HANDLER_DEFINITION_BEGIN(MasterImp, WorkerDone, WorkerDoneMessage)
		
		cout<<"All the workers Done !!! "<<endl;
		evProc.Seppuku();
	
MESSAGE_HANDLER_DEFINITION_END


MESSAGE_HANDLER_DEFINITION_BEGIN(MasterImp, Die, DieMessage)

	evProc.myfile.close();
	cout<<"Number of occurrences "<<evProc.counter<<endl;
	evProc.EventProcessorImp::processDieMessage(evProc,msg);

MESSAGE_HANDLER_DEFINITION_END

